package com.example.push.service;

import com.example.push.domain.Task;
import com.example.push.dto.UserInfoDTO;
import com.example.push.infa.RemoteAPI;
import com.example.push.repository.TaskRepository;
import com.querydsl.core.types.Predicate;

import io.micrometer.core.annotation.Timed;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor
@Timed(value = "task.controller", description = "任务管理")
public class TaskService {

    private final RemoteAPI remoteAPI;
    private final TaskRepository taskRepository;

    @Transactional(readOnly = true)
    public Page<Task> findAll(Predicate predicate, Pageable pageable) {
        return taskRepository.findAll(predicate, pageable);
    }

    @Timed(value = "task.findById", description = "获取详情", percentiles = {0.5, 0.95, 0.99})
    public Optional<Task> findById(Long id) {

        return taskRepository.findById(id);
    }

    @Transactional
    public Task create(Task task) {
        task.setCreatedAt(LocalDateTime.now());
        task.setUpdatedAt(LocalDateTime.now());
        log.info("create task={}", task);
        return taskRepository.save(task);
    }

    @Transactional
    public Optional<Task> update(Long id, Task taskDetails) {
        return taskRepository.findById(id)
                .map(task -> {
                    task.setName(taskDetails.getName());
                    task.setDescription(taskDetails.getDescription());
                    task.setStatus(taskDetails.getStatus());
                    task.setUpdatedAt(LocalDateTime.now());
                    return taskRepository.save(task);
                });
    }

    @Transactional
    public void delete(Long id) {
        taskRepository.deleteById(id);
    }

    public UserInfoDTO getUserInfo() {
        ResponseEntity<UserInfoDTO> res = remoteAPI.getUserInfo();
        if (!res.hasBody()) {
            log.error("get user info failed");
            throw new RuntimeException("get user info failed");
        }
        return res.getBody();
    }

}